package com.hnichr.ump.common.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.hnichr.ump.common.service.MinioService;
import com.hnichr.ump.common.vo.UploadVO;
import com.mxpioframework.security.entity.User;
import com.mxpioframework.security.service.UserService;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Service
public class MinioServiceImpl implements MinioService {

    private static final Logger logger = LoggerFactory.getLogger(MinioServiceImpl.class);

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket}")
    private String bucket;

    @Value("${minio.resUrl}")
    private String resUrl;

    @Autowired
    private UserService userService;

    @Autowired
    protected PasswordEncoder passwordEncoder;

    @Override
    public UploadVO upload(MultipartFile[] files, String userName, String password) {
        try{
            User user = userService.findByName(userName);
            if(user==null){
                return new UploadVO("用户名或者密码不正确",null);
            }
            if(!passwordEncoder.matches(password,user.getPassword())){
                return new UploadVO("用户名或者密码不正确",null);
            }
        }
        catch (Exception e){
            return new UploadVO("用户名或者密码不正确",null);
        }
        return upload(files);
    }

    public UploadVO upload(MultipartFile[] files){
        List<String> urlList = new ArrayList<>();
        for(MultipartFile file:files){
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.fastUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = DateUtil.format(DateTime.now(), "yyyy/MM/dd") + "/" + fileName;
            try {
                PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucket).object(objectName)
                        .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
                // 文件名称相同会覆盖
                ObjectWriteResponse response = minioClient.putObject(objectArgs);
                String etag = response.etag();
                logger.info(">>>>>>>>>>>>>>>>>>upload file fileName:{},etag:{}",objectName,etag);
                urlList.add(resUrl+"/"+bucket+"/"+objectName);
            } catch (Exception e) {
                return new UploadVO(e.getMessage(),null);
            }
        }
        return new UploadVO(null,urlList);
    }

    public String uploadFile(String file,String contentType){
        String fileName = UUID.fastUUID() + file.substring(file.lastIndexOf("/"));
        try(InputStream inputStream = Files.newInputStream(Paths.get(file))) {
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucket).object(fileName)
                    .stream(inputStream, inputStream.available(), -1).contentType(contentType).build();
            // 文件名称相同会覆盖
            ObjectWriteResponse response = minioClient.putObject(objectArgs);
            String etag = response.etag();
            logger.info(">>>>>>>>>>>>>>>>>>upload file fileName:{},etag:{}",fileName,etag);
            return resUrl+"/"+bucket+"/"+fileName;
        } catch (Exception e) {
            return null;
        }
    }
}
